package ru.kest.babymonitor.gif;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView;

public class GifDecoderView extends ImageView {

    private boolean mIsPlayingGif = false;

    private GifDecoder mGifDecoder;

    private Bitmap mTmpBitmap;

    final Handler mHandler = new Handler();

    Runnable mUpdateResults;

    /*public GifDecoderView(Context context, InputStream stream) {
        super(context);
        playGif(stream);
    }
    */

    public GifDecoderView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void loadGif(int id) {
        mGifDecoder = new GifDecoder();
        mGifDecoder.read(getResources().openRawResource(id));
        mUpdateResults = new Runnable() {
            public void run() {
                if (mTmpBitmap != null && !mTmpBitmap.isRecycled()) {
                    GifDecoderView.this.setImageBitmap(mTmpBitmap);
                }
            }
        };
    }

    public void startRendering() {

        if (mIsPlayingGif) return;

        mIsPlayingGif = true;

        new Thread(new Runnable() {
            public void run() {
                final int n = mGifDecoder.getFrameCount();
                final int ntimes = mGifDecoder.getLoopCount();
                int repetitionCounter = 0;
                do {
                    for (int i = 0; i < n; i++) {
                        mTmpBitmap = mGifDecoder.getFrame(i);
                        int t = mGifDecoder.getDelay(i);
                        mHandler.post(mUpdateResults);
                        try {
                            Thread.sleep(t);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if(ntimes != 0) {
                        repetitionCounter ++;
                    }
                } while (mIsPlayingGif && (repetitionCounter <= ntimes));
            }
        }).start();
    }

    public void stopRendering() {
        mIsPlayingGif = false;
    }

    public boolean isPlaying() {
        return mIsPlayingGif;
    }
}